package com.example.springboot.security;

import com.example.springboot.util.R;
import com.example.springboot.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenLogoutHandler implements LogoutHandler {

    private TokenManager tokenManager;
    private RedisTemplate<String,String> redisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager,RedisTemplate<String,String> redisTemplate){
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 移除
     * @default
    **/
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        // 1.从header获取token
        ObjectMapper objectMapper = new ObjectMapper();
        String token = request.getHeader("token");
        if (token != null) {
            tokenManager.removeToken();
        }
        String username = tokenManager.getUserInfo(token);
        // token 不为空，移除token，从redis删除token
        // TODO
        ResponseUtil.out(response,R.ok());
    }

}
